package org.sun.online.internal.common.trace;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;
import org.sun.online.internal.common.utils.SnowFlakeId;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author sunhongmin
 * @date 2022/5/26 20:39
 * @description
 */
@WebFilter(urlPatterns = "/*", filterName = "traceIdFilter")
@Order(1)
@Slf4j
public class TransIdFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取前端请求中的traceId 设置到MDC中，为空则生成雪花ID
        HttpServletRequest req = (HttpServletRequest) request;
        String traceId = req.getHeader(TraceIdUtils.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = SnowFlakeId.nextId();
        }
        TraceIdUtils.setTraceId(traceId);
        log.info((String.format("URI--%s", ((HttpServletRequest) request).getRequestURI())));
        chain.doFilter(request, response);
    }

}
